package com.ruoyi.file.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.file.FileUtils;
import com.ruoyi.file.service.ISysFileService;
import com.ruoyi.system.api.domain.SysFile;

import java.util.Map;

/**
 * 文件请求处理
 * 
 * @author tanglp
 */
@RestController
public class SysFileController
{
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private Map<String, ISysFileService> sysFileServiceMap; // 自动注入所有策略，Key【格式】: minioSysFileServiceImpl

    /**
     * 文件上传请求
     * @param storageType 存储类型（minio/local/fastdfs），不传默认为 minio
     */
    @PostMapping("upload")
    public R<SysFile> upload(@RequestParam MultipartFile file,
                             @RequestParam(required = false, defaultValue = "minio") String storageType)
    {
        try
        {
            String beanName = storageType.toLowerCase() + "SysFileServiceImpl";
            ISysFileService sysFileService = sysFileServiceMap.get(beanName);

            if (sysFileService == null) {
                return R.fail("不支持的存储类型: " + storageType);
            }

            String url = sysFileService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }
}